package com.hxut.filter;

import cn.hutool.core.util.StrUtil;
import com.hxut.entity.SysUser;
import com.hxut.service.SysUserService;
import com.hxut.service.impl.SysUserServiceImpl;
import com.hxut.service.impl.UserDetailServiceImpl;
import com.hxut.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import io.netty.util.internal.StringUtil;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Objects;

/**
 * description: JwtAuthenticationFilter
 * date: 2022/7/10 10:24
 * author: MR.孙
 */
public class JwtAuthenticationFilter extends BasicAuthenticationFilter {

    @Autowired
    private JwtUtils jwtUtils;

    @Autowired
    private UserDetailServiceImpl userDetailsService;

    @Autowired
    private SysUserService userService;

    public JwtAuthenticationFilter(AuthenticationManager authenticationManager) {
        super(authenticationManager);
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {

        //获取jwt
        String jwt = request.getHeader(jwtUtils.getHeader());
        if(StrUtil.isBlankOrUndefined(jwt)){
            chain.doFilter(request,response);
            return ;
        }

        //解析jwt
        Claims claim = jwtUtils.getClaimByToken(jwt);
        if(claim==null){
            throw new JwtException("token异常");
        }
        //如果jwt过期
        if(jwtUtils.isTokenExpired(claim)){
            throw new JwtException("token已过期");
        }

        //获取主体
        String username = claim.getSubject();

        //根据用户名获取用户信息
        SysUser sysUser = userService.getByUsername(username);

        //封装authentication信息
        UsernamePasswordAuthenticationToken token=
                new UsernamePasswordAuthenticationToken(username,null,userDetailsService.getAuthentication(sysUser.getId()));

        //存入security上下文中,方便后面的过滤器好调用
        SecurityContextHolder.getContext().setAuthentication(token);

        //放行
        chain.doFilter(request,response);

    }
}
